package com.easou.ps.master.util;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpClientTools{
	private static final Logger LOG = Logger.getLogger("common");
	private static final int CONNECTIONS_MAX_TOTAL = 3;
	private static final int TIME_OUT_CONN = 10 * 1000;
	private static final int TIME_OUT_SOCKET = 20 * 1000;
	public static HttpClient httpClient;

	static {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, TIME_OUT_CONN);
		HttpConnectionParams.setSoTimeout(params, TIME_OUT_SOCKET);
		ConnManagerParams.setMaxTotalConnections(params, CONNECTIONS_MAX_TOTAL);
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
		httpClient = new DefaultHttpClient(connectionManager, params);
	}
	

	public static byte[] getHttpResPonseBody(String url) {
		byte[] result = null;
		if (url == null) {
			return result;
		}
		HttpGet get = null;
		try {
			get = new HttpGet(url);
			HttpResponse response = httpClient.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				return EntityUtils.toByteArray(response.getEntity());
			}
		} catch (Exception e) {
			LOG.error(url + ":: 访问失败... ", e);
		} finally {
			if (get != null) {
				get.abort();
			}
		}
		return result;
	}
    
	public static String getHttpResPonseBody(String url, String encoding) {
		byte[] result = getHttpResPonseBody(url);
		String body = null;
		if (result == null) {
			return body;
		} else {
			try {
				body = new String(result, encoding);// "UTF-8"
			} catch (UnsupportedEncodingException e) {
				LOG.error(url + ":: encoding error... ", e);
			}
		}
		return body;
	}
	
	public static void main(String[] args) {
//		System.out.println(getHttpResPonseBody("http://www.baidu.com/", "gbk"));
		System.out.println(getHttpResPonseBody("http://test.ps.easou.com:8080/", "UTF-8"));
	}
}
